<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Code by TinhNQ
 * 2014
 **/
class Dish_model extends MY_Model {

    protected $dish;

    /**
     * [__construct description]
     */
    function __construct(){
        parent::__construct();
    }

    function table_name(){
        return "dishs";
    }

    /**
     * [get_dishs description]
     * @param  array   $filters  [description]
     * @param  boolean $counting [description]
     * @return [type]            [description]
     */
    function get_dishs($filters = array(),$counting = false){
        if (isset($this->CI->cache)){
            $caching = true;
            $cache_key = 'ci_Dish_'.md5(serialize($filters));
            if ($counting){
                $cache_key = 'ci_Dish_COUNT_'.md5(serialize($filters));
            }
            if ($return = $this->cache->file->get($cache_key)) {
                return ($return == 'empty_cache') ? FALSE : $return;
            }
        } else {
            $caching = false;
        }

        if (isset($filters['category_id']) || isset($filters['dish_category']) || isset($filters['frontend'])) {
            $this->db->select('dishs.*, cn.category_id as category_id, cc.name as category_name, cc.alias AS category_alias');
            $this->db->join('categories_dish as cn','cn.dish_id = dishs.dish_id','left');
            $this->db->join('categories as cc','cc.category_id = cn.category_id','left');
            $this->db->from('dishs');
        } else {
            $this->db->select('dishs.*');
            $this->db->from('dishs');
        }

        if (isset($filters['category_id'])){
            $this->db->where('(cc.category_id ='.$filters['category_id'].' OR cc.parent_id ='.$filters['category_id'].')');
        }
        if (isset($filters['dish_category'])){
            $this->db->where('cc.category_id', $filters['dish_category']);
        }
        if (isset($filters['array_dish_id'])) {
            $this->db->where_in('dishs.dish_id', $filters['array_dish_id']);
        }
        if (isset($filters['dish_id'])) {
            $this->db->where('dishs.dish_id', $filters['dish_id']);
        }
        if (isset($filters['dish_id_other'])) {
            $this->db->where('dishs.dish_id !=', $filters['dish_id_other']);
        }
        if (isset($filters['name'])) {
            $this->db->like('dishs.name', $filters['name']);
        }
        if (isset($filters['alias'])) {
            $this->db->where('dishs.alias', $filters['alias']);
        }
        if (isset($filters['introtext'])) {
            $this->db->where('dishs.introtext', $filters['introtext']);
        }
        if (isset($filters['is_hot'])) {
            $this->db->where('dishs.is_hot', $filters['is_hot']);
        }
        if (isset($filters['status'])) {
            $this->db->where('dishs.status', $filters['status']);
        }
        if (isset($filters['rawmaterial'])) {
            $this->db->where('dishs.rawmaterial', $filters['rawmaterial']);
        }
        if (isset($filters['fulltext'])) {
            $this->db->where('dishs.fulltext', $filters['fulltext']);
        }
        if (isset($filters['is_spec'])) {
            $this->db->where('dishs.is_spec', $filters['is_spec']);
        }
        if (isset($filters['tags'])) {
            $this->db->like('dishs.tags', $filters['tags']);
        }
        if (isset($filters['limit'])) {
            $offset = (isset($filters['page'])) ? $filters['page'] : 0;
            $this->db->limit($filters['limit'], $offset);
        }
        $this->db->group_by('dishs.dish_id');
        $this->db->order_by('dishs.created','DESC');

        $result = $this->db->get();

        if($counting != false) {
            $rows = $result->num_rows();
            $result->free_result();

            if ($caching == TRUE) {
                $this->CI->cache->file->save($cache_key, $rows, (5*60));
            }

            return $rows;
        }
        if ($result->num_rows() == 0) {
            return false;
        }
        $dish = array();
		$dish = $this->create_information_dish($result->result_array());
        
        if ($caching){
            $this->CI->cache->file->save($cache_key, $dish);
        }
        $result->free_result();

        return $dish;
    }

    function get_count($filter = array()){
        return $this->get_dishs($filter,true);
    }

    function get_dish($dishId){
        if (!isset($this->dish[$dishId])){
            $dish = $this->get_dishs(array('dish_id'=>$dishId));
            $this->dish[$dishId] = $dish;
        }else{
            $dish = $this->dish[$dishId];
        }
        if (empty($dish)) {
            return false;
        }
        return $dish[0];
    }

    function insert_dish($data){
        $dish_id = $this->save($data);
		$this->process_category_dish($data, $dish_id, false);
		$this->process_stocks_steps($dish_id, $data);

        return $dish_id;
    }

    function update_dish($data, $dish_id) {
		$this->process_category_dish($data, $dish_id);
		$this->process_stocks_steps($dish_id, $data);

        return $this->update($data, array('dish_id' => $dish_id));
    }

    function delete_dish($dish_id) {
        $this->delete_image_file($dish_id);

        $this->db->delete('steps', array('dish_id' => $dish_id));
        $this->db->delete('stocks', array('dish_id' => $dish_id));
        $this->db->delete('categories_dish', array('dish_id' => $dish_id));

        return $this->delete(array('dish_id'=>$dish_id));
    }

    function delete_image_file($dish_id) {
        $files = $this->db->select('image1')->from('dishs')->where('dish_id', $dish_id)->get()->result_array();

        foreach ($files[0] as $k=>$v){
            if (file_exists($v)){
                unlink($v);
            }
        }

        $arrSteps = $this->get_steps($dish_id);
        foreach ($arrSteps as $key => $value) {
            $v = $value['image'];
            if (file_exists($v)) {
                unlink($v);
            }
        }
    }
    
    function change_status_dish($dish_id, $change = 1) {
        $result = $this->db->update('dishs', array('status' => $change, 'created' => date("Y-m-d H:i:s")), array('dish_id' => $dish_id));
        $this->after_update();
        if (isset($this->CI->cache)) {
            $this->CI->cache->file->clean();
        }
        return $result;
    }

    function get_dish_by_alias($dish_alias){
        $dish = $this->get_dishs(array('alias'=>$dish_alias, 'frontend' => 1, 'status' => 1),false);
        if ($dish){
            return $dish[0];
        }
        return false;
    }

    function get_category_dish($dish_id, $getid = 1) {
        $this->db->select('*');
        $this->db->from('categories_dish');
        $this->db->where('dish_id', $dish_id);

		$array = array();
		if ($getid != 1)
		{
			$this->db->join('categories', 'categories_dish.category_id = categories.category_id');
			$result = $this->db->get();
			foreach ($result->result() as $row)
	        {
	            $array[] = array ('name' => $row->name, 'alias' => $row->alias);
	        }
			return $array;
		}
		
		$result = $this->db->get();
        foreach ($result->result() as $row)
        {
            $array[] = $row->category_id;
        }

        return $array;
    }
	
	function get_stocks($dish_id) {
        $this->db->select('*');
        $this->db->from('stocks');
        $this->db->where('dish_id', $dish_id);
		
		$result = $this->db->get();
        $array = array();
        foreach ($result->result() as $row)
        {
            $array[] = array('stock' => $row->stock, 'count' => $row->count);
        }
        return $array;
    }

	function get_steps($dish_id, $count = 0) {
        $this->db->select('*');
        $this->db->from('steps');
        $this->db->where('dish_id', $dish_id);
		
		if ($count == 1)
		{
			return $this->db->count_all_results();			
		}
		
        $result = $this->db->get();

        $array = array();
        foreach ($result->result() as $row)
        {
            $array[] = array('image' => $row->image, 'comment' => $row->comment);
        }
        return $array;
    }
	
	function process_stocks_steps($dish_id, $arrData) {
		//$this->db->trans_begin();
		//#EBEBEB
		// delete records by dish_id
		$this->db->delete('stocks', array('dish_id' => $dish_id));
		$this->db->delete('steps', array('dish_id' => $dish_id)); 
		
		// insert records
		$arrStocks = array();
		foreach($arrData['stock'] as $key => $val)
		{
			if($val != "") {
				$arrStocks[] = array('stock' => $val, 'count' => $arrData['count'][$key], 'dish_id' => $dish_id);	
			}
		}

        foreach($arrData['steps'] as $key => $val)
        {
            if($val != "") {
                $arrData['steps'][$key]['dish_id'] =  $dish_id;   
            }
        }

		$this->db->insert_batch('stocks', $arrStocks);
		$this->db->insert_batch('steps', $arrData['steps']);

		/*
		if ($this->db->trans_status() === FALSE)
		{
		    $this->db->trans_rollback();
			return FALSE;
		}
		
		$this->db->trans_commit();
		*/
		return TRUE;
	}

    function get_categories_options($filters=array()){
        $categories_options = array();
        $categories = $this->get_categories($filters);
        if (is_array($categories) && count($categories)){
            foreach ($categories as $category){
                $categories_options[$category['category_id']] = $category['treename'];
            }
        }
        return $categories_options;
    }

    /**
     * get categories
     * @param  array   $filters     [description]
     * @param  boolean $counting    [description]
     * @param  boolean $treerecurse [description]
     * @return [type]               [description]
     */
    function get_categories($filters = array(),$counting = false,$treerecurse = true) {
		$filters = array_merge($filters, array('status' => '1'));
		
        $this->CI->load->model('categories/categories_model');
        $filters = array_merge(array('module'=>'dish'),$filters);
        $cactegory_news = $this->categories_model->get_categories($filters,$counting);
        if ($counting){
            return $cactegory_news;
        }
        if ($treerecurse){
            $list_categories = array();
            if (is_array($cactegory_news) && count($cactegory_news)> 0){
                $children = array();
                foreach ($cactegory_news as $v){
                    $v['id'] = $v['category_id'];
                    $pt = $v['parent_id'];
                    $list = isset($children[$pt]) ? $children[$pt] : array();
                    array_push( $list, $v );
                    $children[$pt] = $list;
                }
                $list_categories = treerecurse(0,'',array(), $children,99999);
            }
            return $list_categories;
        }else{
            if ($cactegory_news){
                return $cactegory_news;
            }
        }
        return false;
    }

    function get_count_categories($filters = array()) {
        return $this->get_categories($filters,true);
    }

	function process_category_dish($data, $dish_id, $update = 1) {
		if(isset($update) && $update > 0) {
			$this->delete(array('dish_id' => $dish_id), 'categories_dish');	
		}
		
		$arr_id = $data['category_id'];
        if (is_array($arr_id)) {
			$arrCategories = array();
			foreach($arr_id as $key => $val)
			{
				if($val != "") {
					$arrCategories[] = array('category_id' => $val, 'dish_id' => $dish_id, 'position' => 1);	
				}
			}
			$this->db->insert_batch('categories_dish', $arrCategories);
        }
	}

    function get_categories_dish() {
        $this->CI->load->model('categories/categories_model');

        $filters = array('status' => '1', 'module'=>'dish', 'parent_id' => '4'); // 4 is parent_id cua mon ngon
        $data = $this->categories_model->get_categories($filters);

        $data_new = array();
        foreach ($data as $value) {
            $key = $value['category_id'];
            $data_new[$key] = $value;

            $filtersub = array('status' => '1', 'module'=>'dish', 'parent_id' => $key);
            $data_sub = $this->categories_model->get_categories($filtersub);
            $data_new[$key]['sub_categories'] = $data_sub;
        }

        return $data_new;
    }

    function get_categories_style_dish() {
        $sql = "SELECT c.category_id, c.parent_id, c.module, c.alias, c.name, c.ordering, c.created, Count(cd.dish_id) AS `count`, c.alias 
                FROM `categories` as c 
                LEFT JOIN categories_dish as cd ON c.category_id = cd.category_id 
                inner JOIN dishs as d ON d.dish_id = cd.dish_id
                WHERE c.parent_id =  134 AND c.status =  '1' AND d.status =  '1'  
                GROUP BY c.category_id ORDER BY `count` DESC, c.ordering ASC";
        // 134 is parent_id cua phong cach nau
        $query = $this->db->query($sql);
        $data = array();
        if ($query->num_rows() > 0)
        {
            foreach ($query->result_array() as $category)
            {
                $category['link'] = create_url('dish/'.$category['alias'],array('rewrite'=>true));
                $data[] = $category;
            }
        }
        return $data;
    }

    function get_random_dish($limit = 3)
    {
        $this->db->select('dish_id');
        $this->db->order_by('dish_id', 'RANDOM');
        $this->db->where('status', 1);
        $this->db->limit($limit);
        $query = $this->db->get('dishs');
        $array = $query->result_array();
        $ids = array();
        foreach ($array as $value) {
           $ids[] = $value['dish_id'];
        }

        $data = $this->get_dishs(array('array_dish_id' => $ids, 'frontend' => 1, 'status' => 1));
        return $data;
    }

    function create_information_dish($array_in) {
        $array_out = array();
        foreach ($array_in as $row ){
            if (isset($row['category_alias'])) {
                $row['link'] = create_url('dish/'. $row['category_alias'].'/'.$row['alias'],array('rewrite'=>true));
            }
            
            $total = $this->get_steps($row['dish_id'], 1);

            $title = $total . " bước nấu món " . $row['name'];
            $row['title'] = ucfirst(strtolower($title));
            $row['date'] = fdate($row['created'],"%A, %d/%m/%Y");

            $row['new'] = false;
            if(strtotime($row['created']) > strtotime('-7 day') ) {
                $row['new'] = true;
            }

            $array_out[] = $row;
        }

        return $array_out;
    }

    function update_dishs_view($dish_id) {
        $sql = "update dishs d, (SELECT view FROM `dishs` where dish_id = $dish_id) cur
                 set d.view = (cur.view + 1)
                where d.dish_id = $dish_id";
        $this->db->query($sql);
    }

    function update_dishs_public() {

        $dish = $this->get_dishs(array('status'=> 0, 'limit' => 1));
        $dish_id = $dish[0]['dish_id'];

        $this->change_status_dish($dish[0]['dish_id']);
    }
}
?>